package org.tarena.dang.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class DynamicImageUtil {
	private static final String[] CHARS = { "A", "B", "C", "D", "E", "1", "2",
			"3", "4", "5", "1", "2", "3", "4", "5" };
	private static final int WIDTH = 200;
	private static final int HEIGHT = 100;
	private static final int LINES = 50;
	private static final int LEN = 5;

	public static Map<String, BufferedImage> getDynamicImage() {
		BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
				BufferedImage.TYPE_INT_RGB);
		Graphics graph = image.getGraphics();
		graph.setColor(Color.WHITE);
		graph.fillRect(0, 0, WIDTH, HEIGHT);
		Random ran = new Random();
		String code = "";
		// 画随机生成的Code
		for (int i = 0; i < LEN; i++) {
			String chs = CHARS[ran.nextInt(CHARS.length)];
			code += chs;
			graph.setColor(Color.RED);
			graph.setFont(new Font(null, Font.BOLD + Font.ITALIC, 40));
			graph.drawString(chs, i * (WIDTH / LEN), HEIGHT*2/5);
		}

		// 画干扰线
		for (int i = 0; i < LINES; i++) {
			graph.setColor(new Color(ran.nextInt(256), ran.nextInt(256), ran
					.nextInt(256)));
			graph.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT),
					ran.nextInt(WIDTH), ran.nextInt(HEIGHT));
		}
		Map<String, BufferedImage> map = new HashMap<String, BufferedImage>();
		map.put(code, image);
		return map;
	}

	public static InputStream getInputStream(BufferedImage image) {
		// 将BufferedImage编码成JPEG格式
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		JPEGImageEncoder encode = JPEGCodec.createJPEGEncoder(bos);
		try {
			encode.encode(image);
			// 将bos中的保存的JPEG图片信息，封装成ByteArrayInputStream
			byte[] bys = bos.toByteArray();
			InputStream fstream = new ByteArrayInputStream(bys);
			return fstream;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
